package com.work.yshop.ui.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.tabs.TabLayout;
import com.work.yshop.R;
import com.work.yshop.adapter.OrderAdapter;
import com.work.yshop.model.Order;
import com.work.yshop.mvp.contract.OrderContract;
import com.work.yshop.mvp.presenter.OrderPresenter;

import java.util.List;

/**
 * 订单管理页面 - 卖家查看和管理订单 - MVP架构
 */
public class OrderManageActivity extends AppCompatActivity implements OrderContract.View {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private RecyclerView recyclerView;
    private View emptyView;
    private OrderAdapter adapter;
    private FloatingActionButton fabAddOrder;
    private ProgressBar progressBar;
    
    // 订单状态
    private static final int STATUS_ALL = 0;
    private static final int STATUS_PENDING = 1;
    private static final int STATUS_PROCESSING = 2;
    private static final int STATUS_SHIPPED = 3;
    private static final int STATUS_COMPLETED = 4;
    private static final int STATUS_CANCELED = 5;
    
    private int currentStatus = STATUS_ALL;
    private OrderContract.Presenter presenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_manage);
        
        // 初始化Presenter
        presenter = new OrderPresenter(this);
        presenter.attachView(this);
        
        initViews();
        setupToolbar();
        setupTabLayout();
        
        // 加载订单数据
        presenter.loadOrders(STATUS_ALL);
    }
    
    private void initViews() {
        toolbar = findViewById(R.id.toolbar);
        tabLayout = findViewById(R.id.tab_layout);
        recyclerView = findViewById(R.id.recycler_view);
        emptyView = findViewById(R.id.empty_view);
        fabAddOrder = findViewById(R.id.fab_add_order);
        progressBar = findViewById(R.id.progress_bar);
        
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new OrderAdapter();
        recyclerView.setAdapter(adapter);
        
        adapter.setOnItemClickListener(position -> {
            Order order = adapter.getItem(position);
            if (order != null) {
                // 查看订单详情
                Toast.makeText(this, "查看订单: " + order.getOrderNumber(), Toast.LENGTH_SHORT).show();
            }
        });
        
        adapter.setOnActionClickListener((position, action) -> {
            Order order = adapter.getItem(position);
            if (order != null) {
                switch (action) {
                    case OrderAdapter.ACTION_ACCEPT:
                        presenter.acceptOrder(order);
                        break;
                    case OrderAdapter.ACTION_SHIP:
                        presenter.shipOrder(order);
                        break;
                    case OrderAdapter.ACTION_CANCEL:
                        presenter.cancelOrder(order);
                        break;
                }
            }
        });
        
        // 添加长按删除功能
        adapter.setOnItemLongClickListener(position -> {
            Order order = adapter.getItem(position);
            if (order != null) {
                showDeleteConfirmDialog(order);
            }
            return true;
        });
        
        // 添加新订单按钮点击事件
        fabAddOrder.setOnClickListener(v -> {
            showAddOrderDialog();
        });
    }
    
    private void setupToolbar() {
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle("订单管理");
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }
        
        toolbar.setNavigationOnClickListener(v -> onBackPressed());
    }
    
    private void setupTabLayout() {
        tabLayout.addTab(tabLayout.newTab().setText("全部"));
        tabLayout.addTab(tabLayout.newTab().setText("待接单"));
        tabLayout.addTab(tabLayout.newTab().setText("处理中"));
        tabLayout.addTab(tabLayout.newTab().setText("已发货"));
        tabLayout.addTab(tabLayout.newTab().setText("已完成"));
        tabLayout.addTab(tabLayout.newTab().setText("已取消"));
        
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                presenter.loadOrders(tab.getPosition());
            }
            
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }
            
            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }
    
    private String getEmptyMessage(int status) {
        switch (status) {
            case STATUS_PENDING:
                return "暂无待接单订单";
            case STATUS_PROCESSING:
                return "暂无处理中订单";
            case STATUS_SHIPPED:
                return "暂无已发货订单";
            case STATUS_COMPLETED:
                return "暂无已完成订单";
            case STATUS_CANCELED:
                return "暂无已取消订单";
            default:
                return "暂无订单";
        }
    }

    /**
     * 显示添加订单对话框
     */
    private void showAddOrderDialog() {
        // 创建对话框布局
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_add_order, null);
        EditText etBuyerName = dialogView.findViewById(R.id.et_buyer_name);
        EditText etAmount = dialogView.findViewById(R.id.et_amount);
        
        // 创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("添加订单")
                .setView(dialogView)
                .setPositiveButton("添加", (dialog, which) -> {
                    // 获取输入内容
                    String buyerName = etBuyerName.getText().toString().trim();
                    String amountStr = etAmount.getText().toString().trim();
                    
                    if (buyerName.isEmpty() || amountStr.isEmpty()) {
                        Toast.makeText(this, "请填写完整信息", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    
                    try {
                        double amount = Double.parseDouble(amountStr);
                        presenter.addOrder(buyerName, amount);
                    } catch (NumberFormatException e) {
                        Toast.makeText(this, "请输入有效金额", Toast.LENGTH_SHORT).show();
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }
    
    /**
     * 显示删除确认对话框
     */
    private void showDeleteConfirmDialog(Order order) {
        // 确认删除对话框
        new AlertDialog.Builder(this)
                .setTitle("删除订单")
                .setMessage("确定要删除订单 " + order.getOrderNumber() + " 吗？")
                .setPositiveButton("删除", (dialog, which) -> {
                    presenter.deleteOrder(order);
                })
                .setNegativeButton("取消", null)
                .show();
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (presenter != null) {
            presenter.detachView();
        }
    }
    
    // OrderContract.View接口实现
    @Override
    public void showLoading() {
        if (progressBar != null) {
            progressBar.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void hideLoading() {
        if (progressBar != null) {
            progressBar.setVisibility(View.GONE);
        }
    }

    @Override
    public void showOrders(List<Order> orders) {
        currentStatus = tabLayout.getSelectedTabPosition();
        
        if (recyclerView != null && adapter != null) {
            recyclerView.setVisibility(View.VISIBLE);
            emptyView.setVisibility(View.GONE);
            adapter.setData(orders);
        }
    }

    @Override
    public void showEmptyView(int status) {
        currentStatus = status;
        
        if (recyclerView != null && emptyView != null) {
            recyclerView.setVisibility(View.GONE);
            emptyView.setVisibility(View.VISIBLE);
            ((TextView) emptyView.findViewById(R.id.tv_empty_message)).setText(getEmptyMessage(status));
        }
    }

    @Override
    public void showError(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showOperationResult(boolean success, String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }
} 